package com.example.qxfw.qxxx.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.dmgis.entity.DmMapPoint;
import com.dmgis.service.DmServiceConnector;
import com.dmgis.weblib.MapCommon;
import com.example.qxfw.common.SysResult;
import com.example.qxfw.common.entity.qx.*;
import com.example.qxfw.common.entity.xt.ContourSetting;
import com.example.qxfw.common.entity.xt.SysConfig;
import com.example.qxfw.common.entity.zy.BaseProduct;
import com.example.qxfw.common.entity.zy.RainWaterShed;
import com.example.qxfw.common.entity.zy.ReservoirWaterInfo;
import com.example.qxfw.common.entity.zy.RiverBasin;
import com.example.qxfw.common.util.TxtFileManager;
import com.example.qxfw.common.util.WeatherInfoUtil;
import com.example.qxfw.qxxx.dto.MsgDto;
import com.example.qxfw.qxxx.dto.MsgdiumSmallScalDto;
import com.example.qxfw.qxxx.service.*;
import com.example.qxfw.rcyw.pojo.JobMake;
import com.example.qxfw.rcyw.service.JobMakeService;
import com.example.qxfw.rcyw.service.SmallScaleStationService;
import com.example.qxfw.ybzz.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.example.qxfw.common.util.StringUtil.toNull;

@Slf4j
@Api(tags = "气象信息-区域自动站接口")
@RestController
@CrossOrigin
@RequestMapping("/RegionalAutomaticStationController")
public class RegionalAutomaticStationController {

    private static final String pluginClassFullName = "service";

    private static final String methodName = "contour";

    @Value("${txt.file.txtIp}")
    private String txtIp;

    @Value("${txt.file.txtPort}")
    private String txtPort;

    @Value("${server.servlet.context-path}")
    private String path;

    @Value("${dmgis.serName}")
    private String serverName;

    @Value("${dmgis.ip}")
    private String dmip;

    @Value("${dmgis.port}")
    private String port;

    @Value("${dmgis.rect}")
    private String rect;

    @Value("${dmgis.image_url}")
    private String imageUrl;

    @Autowired
    private TxtFileManager txtFileManager;

    @Autowired
    private RefinedForecastingService refinedForecastingService;

    @Autowired
    private RegionalAutomaticStationService regionalAutomaticStationService;

    @Autowired
    private SmallScaleStationService smallScaleStationService;

    @Autowired
    private SysConfigService sysConfigService;

    @Autowired
    private IssuerInfoService issuerInfoService;

    @Autowired
    private WeatherService weatherService;

    @Autowired
    private MsgMediumSmallScaleService msgMediumSmallScaleService;

    @Autowired
    private RiverBasinService riverBasinService;

    @Autowired
    private BaseProductService baseProductService;

    @Autowired
    private JobMakeService jobMakeService;

    @Autowired
    private WaterService waterService;

    @Autowired
    private ReservoirWaterInfoService reservoirWaterInfoService;

    @Autowired
    private ForecastInfoService forecastInfoService;

    @ApiOperation("气象信息-区域自动站接口-获取站点名称")
    @GetMapping("/getStationName")
    public SysResult getStationName() {
        List<String> stationName = smallScaleStationService.getStationName();
        return SysResult.success(stationName);
    }

    @ApiOperation("气象信息-区域自动站接口获取站点id")
    @GetMapping("/getStationId")
    public SysResult getStationId(String stationName) {
        List<String> stationId = smallScaleStationService.getStationId(stationName);
        return SysResult.success(stationId);
    }

    @ApiOperation("气象信息-区域自动站接口-获取站点数据")
    @GetMapping("/getSmallScale")
    public SysResult getSmallScale() {
        List<SmallScaleStation> scaleStations = smallScaleStationService.getList2();
        return SysResult.success(scaleStations);
    }

    @ApiOperation("气象信息-区域自动站接口-更新监控模板")
    @PostMapping("/updateSysConfig")
    public SysResult updateSysConfig(SysConfig sysConfig) {
        Integer rows = sysConfigService.updateByParamName(sysConfig);
        return SysResult.success(rows);
    }

    @ApiOperation("气象信息-区域自动站接口-获取签发人信息")
    @PostMapping("/getIssuerInfo")
    public SysResult getIssuerInfo() {
        List<String> userName = issuerInfoService.getUserName();
        return SysResult.success(userName);
    }

    @ApiOperation("气象信息-区域自动站接口-获取天气代码表")
    @GetMapping("/getWeather")
    public SysResult getWeather() {
        List<Weather> weathers = weatherService.getWeather();
        return SysResult.success(weathers, weathers.size());
    }

    @ApiOperation("气象信息-区域自动站接口-获取风力代码表")
    @GetMapping("/getWind")
    public SysResult getWind() {
        List<Weather> weathers = weatherService.getWind();
        return SysResult.success(weathers, weathers.size());
    }

    @ApiOperation("气象信息-区域自动站接口-获取风向代码表")
    @GetMapping("/getWindd")
    public SysResult getWindd() {
        List<Weather> weathers = weatherService.getWindd();
        return SysResult.success(weathers, weathers.size());
    }

    @ApiOperation("气象信息-区域自动站接口-获取最新时间")
    @GetMapping("/getMaxTime")
    public SysResult getMaxTime() {
        String maxTime = msgMediumSmallScaleService.getMaxTime();
        return SysResult.success(maxTime);
    }

    @ApiOperation("气象信息-区域自动站接口-多时段查询1")
    @GetMapping("/getStationByMultiSolt")
    public SysResult getStationByMultiSolt(String strSelElement, String strSelWindD, String pdtStart, String pdtEnd, String m_strSelDbName, String strWindDElement, String strwhere) {
        List<MsgMediumSmallScale> list = msgMediumSmallScaleService.getList16(strSelElement, strSelWindD, pdtStart, pdtEnd, m_strSelDbName, strWindDElement, strwhere);
        return SysResult.success(list);
    }

    @ApiOperation("气象信息-区域自动站接口-获取自动站雨量实况")
    @GetMapping("/getMsgMediumSmallScale")
    public SysResult getMsgMediumSmallScale(String observTime1, String observTime2, String city) {
        List<MsgMediumSmallScale> sumRain = msgMediumSmallScaleService.getSumRain(observTime1, observTime2, city);
        return SysResult.success(sumRain);
    }

    @ApiOperation("气象信息-区域自动站接口-获取流域区")
    @GetMapping("/getRiverBasin")
    public SysResult getRiverBasin() {
        List<RiverBasin> list = riverBasinService.list();
        return SysResult.success(list);
    }

    @ApiOperation("气象信息-区域自动站接口-获取基本产品信息")
    @GetMapping("/getBaseProduct")
    public SysResult getBaseProduct(String productName, String productType) {
        List<BaseProduct> list = baseProductService.getList2(productName, productType);
        return SysResult.success(list);
    }

    @ApiOperation("气象信息-区域自动站接口-更新基本产品信息")
    @PostMapping("/updateBaseProduct")
    public SysResult updateBaseProduct(@RequestBody BaseProduct baseProduct) {
        Integer rows = baseProductService.updateProduct(baseProduct);
        return SysResult.success(rows);
    }

    @ApiOperation("气象信息-区域自动站接口-保存基本产品信息")
    @PostMapping("/saveBaseProduct")
    public SysResult saveBaseProduct(@RequestBody BaseProduct baseProduct) {
        Integer rows = baseProductService.save(baseProduct);
        return SysResult.success(rows);
    }

    @ApiOperation("气象信息-区域自动站接口-更新日常任务")
    @PostMapping("/updateJobMake")
    public SysResult updateJobMake(@RequestBody JobMake jobMake) {
        Integer rows = jobMakeService.update(jobMake);
        return SysResult.success(rows);
    }

    @ApiOperation("气象信息-区域自动站接口-获取水情信息")
    @GetMapping("/getWater")
    public SysResult getWater(String latestObserveTime, String location) {
        List<Water> waters = waterService.listByParams(latestObserveTime, location);
        return SysResult.success(waters);
    }

    @ApiOperation("气象信息-区域自动站接口-获取水库水位信息")
    @GetMapping("/getReservoirWaterInfo")
    public SysResult getReservoirWaterInfo(String observTime, String city) {
        List<ReservoirWaterInfo> reservoirWaterInfos = reservoirWaterInfoService.listByParams(observTime, city);
        return SysResult.success(reservoirWaterInfos);
    }

    @ApiOperation("气象信息-区域自动站接口-获取预报信息")
    @GetMapping("/getForecastInfo")
    public SysResult getForecastInfo(String dataChar, String timeChar, String stationId) {
        List<ForecastInfo> forecastInfos = forecastInfoService.listByParams(dataChar, timeChar, stationId);
        return SysResult.success(forecastInfos);
    }

    /************************
     * @Description :
     * @param  pdtStart，pdtEnd :开始时间，如果结束时间为空则进行精确查询，如果开始时间和结束时间都不为空则进行时间段查询
     * @param m_strSelDbName1 :列名
     * @param m_strSelDbName2 :列名
     * @param city :城市名称
     * @param stationId : 判断是否需要国家站，有值的话就检索5开头的国家站
     * @param orderBy :是否排序，有值就进行 desc 排序
     * @return : com.example.demo.common.SysResult
     ************************/

    @ApiOperation("气象信息-区域自动站接口-获取预报信息")
    @GetMapping("/queryEssentialFactor")
    public SysResult queryEssentialFactor(String pdtStart, String pdtEnd, String m_strSelDbName1, String m_strSelDbName2, String city, String stationId, String orderBy) {
        System.err.println(pdtStart);
        System.err.println(pdtEnd);
        System.err.println(m_strSelDbName1);
        System.err.println(m_strSelDbName2);
        System.err.println(city);
        System.err.println(stationId);
        System.err.println(orderBy);
        List<MsgMediumSmallScale> msgMediumSmallScales = regionalAutomaticStationService.queryList(Timestamp.valueOf(pdtStart), Timestamp.valueOf(pdtEnd), m_strSelDbName1, m_strSelDbName2, city, stationId, orderBy);
        return SysResult.success(msgMediumSmallScales);
    }

    @ApiOperation("气象信息-区域自动站接口-等值图")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "msgListstr", value = "json字符串数组，参考：[{\"longitude\":106.537,\"latitude\":24.3794,\"value\":0.5},{\"longitude\":106.66,\"latitude\":24.505,\"value\":1.5},{\"longitude\":106.501,\"latitude\":24.2428,\"value\":7},{\"longitude\":106.72,\"latitude\":24.3628,\"value\":11}]", dataType = "String", required = true),
            @ApiImplicitParam(name = "elementType", value = "类型，参考：12小时雨量\n" +
                    "24小时雨量\n" +
                    "湿度\n" +
                    "6小时雨量\n" +
                    "风速\n" +
                    "1小时雨量\n" +
                    "雨量\n" +
                    "3小时雨量\n" +
                    "气压\n" +
                    "温度 ", dataType = "String", required = true)
    })
    @GetMapping("/coutView")
    public SysResult coutView(String msgListstr, String elementType) throws IOException {
        List<MsgDto> msgMediumSmallScaleList = JSON.parseArray(msgListstr, MsgDto.class);
        List<ContourSetting> contourSettingList = refinedForecastingService.queryByElementType(elementType);
        StringBuilder txt = new StringBuilder();
        // 添加基本参数
        txt.append("[基本参数]\n");
        //点的个数
        txt.append(msgMediumSmallScaleList.size()).append(",");
        //分级数
        txt.append(contourSettingList.size()).append(",");
        //服务名
        txt.append(serverName + ",1,1.5,5,1,0,0,1\n");
        // 添加数据
        txt.append("[数据]\n");
        msgMediumSmallScaleList.forEach(longitudeLatitudeValue -> {
            txt.append(longitudeLatitudeValue.getLongitude()).append("\t")
                    .append(longitudeLatitudeValue.getLatitude()).append("\t")
                    .append(longitudeLatitudeValue.getValue()).append("\n");
        });
        // 添加分级参数
        txt.append("[分级参数]\n");
        contourSettingList.forEach(contourSetting -> {
            txt.append(contourSetting.getElementvalue()).append(",")
                    .append(contourSetting.getElementcolor()).append(",")
                    .append(contourSetting.getElementcolor()).append(",")
                    .append("1,0,")
                    .append(contourSetting.getElementcolor()).append(",")
                    .append("0,0,0,0").append("\n");
        });
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
        // 生成文件名，格式为时间+RefinedForecastingController
        String txtName = dateFormat.format(new Date()) + "RegionalAutomaticStationController";
        String txtPath = txtFileManager.writeDataToTxtFile(txt.toString(), txtName);
        //文件夹目录
        String homePath = TxtFileManager.extractFolderPath(txtPath);
        // 一小时删除任务
        TxtFileManager.cleanupTempFiles(homePath, 3600000);

        System.err.println("文件存储路径：" + txtPath);
        String url = "http://" + txtIp + ":" + txtPort + "/" + txtName + ".txt";
        System.err.println(url);

        DmServiceConnector conn = new DmServiceConnector(dmip, port);
        String uniqueno = conn.getCallPlugin(pluginClassFullName, methodName, "GetInterpolationWork|" + url);
        System.err.println(uniqueno);
        String imgname = conn.getCallPlugin(pluginClassFullName, methodName, "GetContourPic|" + uniqueno + "|" + serverName + "|500|500|" + rect + "|1");
        Map<String, String> rlt = new HashMap<>();
        rlt.put("imgurl", "http://" + imageUrl + imgname);
        rlt.put("rect", rect);
        return SysResult.success(rlt);
    }

    //<----------------------------------------------------------------------------------------------------------------------------------------------------->

    /**
     * 根据不同条件查询自动站信息
     *
     * @param startTime 开始时间
     * @param endTime   结束时间
     * @param condition 查询条件（如：风速、温度、湿度等）
     * @param area      地点（如：国家站，自动站，0表示不查，1表查）
     * @param num       根据情况查最大值或最小值（2：表示查询最大值，1：表示查询最小值，0：放弃这个查询条件）
     * @return
     */
    @ApiOperation(value = "气象信息-区域自动站接口-根据不同条件查询自动站信息")
    @GetMapping("/getDifferentConditionsOfmsgmediumsmallscale")
    public SysResult getDifferentConditionsOfmsgmediumsmallscale(String startTime, String endTime, String condition, String[] area, Integer num, String rainType) {
        Map<MsgMediumSmallScale, Integer> map = new HashMap<>();
        List<MsgMediumSmallScale> list = msgMediumSmallScaleService.getDifferentConditionsOfmsgmediumsmallscale(startTime, endTime, condition, area, num);
        if (list != null) {
            if (condition.equals("风速")) {
                List<MsgdiumSmallScalDto> dtos = new ArrayList<>();
                for (MsgMediumSmallScale msgMediumSmallScale : list) {
                    MsgdiumSmallScalDto dto = new MsgdiumSmallScalDto();
                    dto.setStationid(msgMediumSmallScale.getStationid());
                    dto.setStationname(msgMediumSmallScale.getStationname());
                    dto.setObservtime(msgMediumSmallScale.getObservtime());
                    dto.setLongitude(msgMediumSmallScale.getLongitude());
                    dto.setLatitude(msgMediumSmallScale.getLatitude());
                    dto.setCounty(msgMediumSmallScale.getCounty());
                    dto.setWinddirect(WeatherInfoUtil.getFX(msgMediumSmallScale.getWinddirect()));
                    dto.setWindvelocity(String.valueOf(msgMediumSmallScale.getWindvelocity()));
                    dtos.add(dto);
                }
                System.err.println(dtos);
                return SysResult.success(dtos);
            }
            if (rainType != null) {
                list.forEach(l -> {
                    Float rain = l.getRain();
                    int color = regionalAutomaticStationService.selectByElementTypeAndValue(rainType, rain);
                    map.put(l, color);
                });
            }
            return SysResult.success(map);
        } else {
            return SysResult.fail("给定的条件中未查询到信息！！！");
        }
    }

    @ApiOperation("气象信息-区域自动站接口-整点温度")
    @GetMapping("/getHourlyTemperature")
    public SysResult getHourlyTemperature(String startTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectHourlyTemperature(Timestamp.valueOf(startTime));
       return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-时间段的平均气温")
    @GetMapping("/getAvgTemp")
    public SysResult getAvgTemp(String startTime, String endTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectAvgTemp(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-时间段的最高气温")
    @GetMapping("/getMaxTemp")
    public SysResult getMaxTemp(String startTime, String endTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectMaxTemp(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-时间段的最低气温")
    @GetMapping("/getMinTemp")
    public SysResult getMinTemp(String startTime, String endTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectMinTemp(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-整点风")
    @GetMapping("/getHourlyWind")
    public SysResult getHourlyWind(String startTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectHourlyWind(Timestamp.valueOf(startTime));
        msgMediumSmallScaleList.forEach(msgMediumSmallScale -> {
            if (StringUtils.isNotBlank(String.valueOf(msgMediumSmallScale.getWindvelocity()))) {
                msgMediumSmallScale.setStationpress(toNull(msgMediumSmallScale.getStationpress()));
            }
            if (StringUtils.isNotBlank(String.valueOf(msgMediumSmallScale.getWinddirect()))) {
                msgMediumSmallScale.setWinddirect(toNull(msgMediumSmallScale.getWinddirect()));
            }
        });
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-极大风")
    @GetMapping("/getExtremeWinds")
    public SysResult getExtremeWinds(String startTime, String endTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectExtremeWinds(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
        msgMediumSmallScaleList.forEach(msgMediumSmallScale -> {
            if (StringUtils.isNotBlank(String.valueOf(msgMediumSmallScale.getWindvelocity()))) {
                msgMediumSmallScale.setStationpress(toNull(msgMediumSmallScale.getStationpress()));
            }
            if (StringUtils.isNotBlank(String.valueOf(msgMediumSmallScale.getWinddirect()))) {
                msgMediumSmallScale.setWinddirect(toNull(msgMediumSmallScale.getWinddirect()));
            }
        });
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-整点湿度")
    @GetMapping("/getHourlyHumidity")
    public SysResult getHourlyHumidity(String startTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectHourlyHumidity(Timestamp.valueOf(startTime));
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-最小湿度")
    @GetMapping("/getExtremeHumidity")
    public SysResult getExtremeHumidity(String startTime, String endTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectMinimumHumidity(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-整点气压")
    @GetMapping("/getHourlyAirPressure")
    public SysResult getHourlyAirPressure(String startTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectHourlyAirPressure(Timestamp.valueOf(startTime));
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-平均气压")
    @GetMapping("/getAverageAirPressure")
    public SysResult getAverageAirPressure(String startTime, String endTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectAverageAirPressure(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-整点雨量")
    @GetMapping("/getHourlyRain")
    public SysResult getHourlyRain(String startTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectHourlyRain(Timestamp.valueOf(startTime));
        return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }

    @ApiOperation("气象信息-区域自动站接口-累计雨量")
    @GetMapping("/getCumulativeRainfall")
    public SysResult getCumulativeRainfall(String startTime, String endTime) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.selectCumulativeRainfall(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
      Float avgRain = msgMediumSmallScaleService.selectAvgRain(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));
      Float  maxRain = msgMediumSmallScaleService.selectMaxRain(Timestamp.valueOf(startTime), Timestamp.valueOf(endTime));

      Map result = new HashMap();
        result.put("avgRain",avgRain);
        result.put("maxRain",maxRain);
        result.put("rainInfo",msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
        return SysResult.success(result);
       // return SysResult.common(msgMediumSmallScaleList.stream().distinct().collect(Collectors.toList()));
    }
    @ApiOperation("生成产品")
    @PostMapping("/createProduct")
    public Object createProduct(String startTime,String endTime,String userName,String productName,String  productType )  {
        Calendar calendar = Calendar.getInstance();
        int year = calendar.get(Calendar.YEAR);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            Date parse = sdf.parse(startTime);
            return msgMediumSmallScaleService.createProduct(year,startTime,endTime,userName,productName,productType,parse);
        } catch (Exception e){
            e.printStackTrace();
            return "时间错误";
        }

    }
    @ApiOperation("气象信息-区域自动站接口-分级值")
    @GetMapping("/getContourSetting")
    public SysResult getContourSetting(String type) {
        List<ContourSetting> msetList = msgMediumSmallScaleService.getContourSetting(type);
        for (ContourSetting set : msetList) {
            int color = set.getElementcolor();
            int b = color & 0xff;
            int g = (color >> 8) & 0xff;
            int r = (color >> 16) & 0xff;
            String color16 = String.format("#%02X%02X%02X", r, g, b);
            set.setElemrntinstruction(color16);
        }
        return SysResult.common(msetList);
    }

    @ApiOperation("气象信息-区域自动站接口-根据县区获取区域内的站点信息")
    @GetMapping("/slelctStationNameByCounty")
    public SysResult slelctStationNameByCounty(String county) {
        List<MsgMediumSmallScale> stationNameList = msgMediumSmallScaleService.selectStationNameByCounty(county);
        if (stationNameList != null) {
            return SysResult.success(stationNameList);
        } else {
            return SysResult.fail("给定的条件中未查询到信息！！！");
        }
    }

    @ApiOperation("气象信息-区域自动站接口-单要素统计图(小时)")
    @GetMapping("/getStatisticalChart")
    public SysResult getStatisticalChart(String county, String stationName, String date1, String date2, String time1, String time2, String element) {
        List<MsgMediumSmallScale> list = regionalAutomaticStationService.getStatisticalChart(county, stationName, date1, date2, time1, time2, element);
        return SysResult.success(list,list.size());
//        return SysResult.common(list);
    }

    @ApiOperation("气象信息-区域自动站接口-单要素统计图(日)")
    @GetMapping("/getStatisticalChartDay")
    public SysResult getStatisticalChartDay(String county, String stationName, String date1, String date2, String time1, String time2, String element) {
        List<MsgMediumSmallScale> list = regionalAutomaticStationService.getStatisticalChartDay(county, stationName, date1, date2, time1, time2, element);

        return SysResult.success(list,list.size());
    }

    @ApiOperation("气象信息-区域自动站接口-河流流域")
    @GetMapping("/getRiverBasinByRainWaterShed")
    public SysResult getRiverBasinByRainWaterShed() {
        List<RainWaterShed> riverBasinFromRainWater = regionalAutomaticStationService.getRiverBasinFromRainWater();
        return SysResult.success(riverBasinFromRainWater);
    }

    @ApiOperation("气象信息-区域自动站接口-多要素查询")
    @RequestMapping(value = "multiFactorSearch")
    public SysResult multiFactorSearch(String startTime, String endTime, String station, String riverName) {
        List<MsgMediumSmallScale> msgMediumSmallScaleList = msgMediumSmallScaleService.multiFactorSearchRiver(startTime, endTime, station);
        List<MsgMediumSmallScale> msgdiumSmallScalDtoList = new ArrayList<>();

        msgMediumSmallScaleList.forEach(msgMediumSmallScale -> {
            if (StringUtils.isNotBlank(String.valueOf(msgMediumSmallScale.getDrybulbtemp()))) {
                msgMediumSmallScale.setDrybulbtemp(toNull(msgMediumSmallScale.getDrybulbtemp()));
            }
            if (StringUtils.isNotBlank(String.valueOf(msgMediumSmallScale.getWindvelocity()))) {
                msgMediumSmallScale.setWindvelocity(toNull(msgMediumSmallScale.getWindvelocity()));
            }
            if (StringUtils.isNotBlank(String.valueOf(msgMediumSmallScale.getRelhumidity()))) {
                msgMediumSmallScale.setRelhumidity(toNull(msgMediumSmallScale.getRelhumidity()));
            }
            if (StringUtils.isNotBlank(String.valueOf(msgMediumSmallScale.getWindvelocity()))) {
                msgMediumSmallScale.setStationpress(toNull(msgMediumSmallScale.getStationpress()));
            }
            if (StringUtils.isNotBlank(String.valueOf(msgMediumSmallScale.getWinddirect()))) {
                msgMediumSmallScale.setWinddirect(toNull(msgMediumSmallScale.getWinddirect()));
            }
        });
        System.err.println(riverName);
        if (StringUtils.isNotBlank(riverName)) {
            List<RainWaterShed> riverBasinFromRainWater = regionalAutomaticStationService.getRainWaterShedByName(riverName);
            riverBasinFromRainWater.forEach(rainWaterShed -> {
                String coordinate = rainWaterShed.getCoordinate();
                List<DmMapPoint> pointList = parseCoordinates(coordinate);
                msgMediumSmallScaleList.forEach(msgdiumSmallScalDto -> {
                    if (MapCommon.pointWithinPolygon(pointList, msgdiumSmallScalDto.getLatitude(), msgdiumSmallScalDto.getLatitude())) {
                        msgdiumSmallScalDtoList.add(msgdiumSmallScalDto);
                    }
                });
            });
            return SysResult.success(msgdiumSmallScalDtoList);
        } else {
            return SysResult.success(msgMediumSmallScaleList);
        }

    }

    public static List<DmMapPoint> parseCoordinates(String input) {
        List<DmMapPoint> mapPoints = new ArrayList<>();
        StringTokenizer tokenizer = new StringTokenizer(input, ";");

        while (tokenizer.hasMoreTokens()) {
            String[] split = tokenizer.nextToken().split(",");
            double x = Double.parseDouble(split[0]);
            double y = Double.parseDouble(split[1]);

            DmMapPoint point = new DmMapPoint();
            point.x = x;
            point.y = y;

            mapPoints.add(point);
        }
        return mapPoints;
    }


}